package com.vivien.example.springbootdemo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vivien.example.springbootdemo.pojo.User;
import com.vivien.example.springbootdemo.exception.UserAlreadyExistsException;
import com.vivien.example.springbootdemo.mapper.UserMapper;
import com.vivien.example.springbootdemo.security.JwtTokenProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenProvider jwtTokenProvider;
    // 用户注册
    public void register(User user) {
        // 查询用户名是否重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", user.getName());
        User existingUser = userMapper.selectOne(queryWrapper);

        if (existingUser != null) {
            throw new UserAlreadyExistsException("用户名已存在");
        }

        // 加密密码
        String encodedPassword = passwordEncoder.encode(user.getPassword());

        user.setName(user.getName());
        user.setPassword(encodedPassword);

        // 插入到数据库
        userMapper.insert(user);
    }
    // 用户登录
    public String login(User user) {
        String name = user.getName();
        String password = user.getPassword();
        // 查询用户是否存在
        User selectUser = userMapper.selectOne(new QueryWrapper<User>().eq("name", name));
        if (selectUser == null) {
            throw new RuntimeException("用户名不存在");
        }

        // 验证密码
        if (!passwordEncoder.matches(password, passwordEncoder.encode(user.getPassword()))) {
            throw new RuntimeException("密码错误");
        }

        // 生成并返回 JWT Token
        return jwtTokenProvider.generateToken(user);
    }
}